
// Copyright (C) 2007 Richard Uhler
// This file is part of Esiply.
//
// Esiply is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License, Version 2,
// as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#include "Completion.h"
#include "Expression.h"
#include "NameValue.h"
#include "NameValueList.h"
#include "Null.h"
#include "Scope.h"
#include "String.h"
#include "VariableStatement.h"

VariableStatement::VariableStatement(NameValueList* vlist)
    : m_vlist(vlist)
{}

Value* VariableStatement::execute_internal(Scope* scope) const
{
    // Ecma 12.2
    // 1. Evaluate VariableDeclarationList
    for (int i = 0; i < m_vlist->size(); i++)
    {
        // 1. Evaluate identifier as in 11.1.2, which references 10.1.4
        Value* id = scope->lookup(m_vlist->get(i)->get_name());
        Expression* exp = m_vlist->get(i)->get_value();

        if (exp)
        {
            // 2. Evaluate initializer
            // 3. Call getValue on initer
            Value* initer = exp->evaluate(scope)->getValue();
            CHECK_EXCEPTION(initer);

            // 4. Call putValue(id, initer)
            id->putValue(initer);
        }

        // 5. Return a string value containing the same sequence of
        // characters as in the Identifier.
        // TODO: huh?
    }

    // 2. Return (normal, empty, empty)
    return new Completion(CT_NORMAL, Null::null, Completion::empty);
}

void VariableStatement::getDeclaredVariables(std::vector<String*>& ids) const
{
    for (int i = 0; i < m_vlist->size(); i++)
    {
        ids.push_back(m_vlist->get(i)->get_name());
    }
}

